﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SH;

namespace MTS
{

    public class MTSSerializer : shSerializer
    {

        private MemoryStream m_binaryStream;
        public MTSSerializer(emReadWriteType rwt = emReadWriteType.emRWT_Write)
        : base(rwt)
        {
            m_binaryStream = new MemoryStream();

            if ((rwt & emReadWriteType.emRWT_Write) == emReadWriteType.emRWT_Write)
            {
                m_writer = new BinaryWriter(m_binaryStream);
            }
            else if ((rwt & emReadWriteType.emRWT_Read) == emReadWriteType.emRWT_Read)
            {
                m_reader = new BinaryReader(m_binaryStream);
            }
        }

        public MTSSerializer(byte[] bytes, emReadWriteType rwt = emReadWriteType.emRWT_Read)
            : base(rwt)
        {
            m_binaryStream = new MemoryStream(bytes);

            if ((rwt & emReadWriteType.emRWT_Write) == emReadWriteType.emRWT_Write)
            {
                m_writer = new BinaryWriter(m_binaryStream);
            }
            else if ((rwt & emReadWriteType.emRWT_Read) == emReadWriteType.emRWT_Read)
            {
                m_reader = new BinaryReader(m_binaryStream);
            }
        }

        public shErrorCode attachBuf(byte[] bytes)
        {
            m_binaryStream = new MemoryStream(bytes);

            if ((m_rwt & emReadWriteType.emRWT_Write) == emReadWriteType.emRWT_Write)
            {
                m_writer = new BinaryWriter(m_binaryStream);
            }
            else if ((m_rwt & emReadWriteType.emRWT_Read) == emReadWriteType.emRWT_Read)
            {
                m_reader = new BinaryReader(m_binaryStream);
            }

            return shErrorCode.sh_ec_Success;
        }

        public byte[] detachBuf()
        {
            if (m_binaryStream != null)
            {
                var b = m_binaryStream.ToArray();
                m_binaryStream = null;
                return b;
            }
            else
                return null;
        }

        public byte[] ToArray()
        {
            //var nLength = m_binaryStream.Length;
            //byte[] buf = new byte[nLength];

            //nLength = m_binaryStream.Read(buf, 0, (int)nLength);

            if (m_binaryStream != null)
                return m_binaryStream.ToArray();
            else
                return null;
        }

    }

}
